<template>
  <div>
    <el-form style="max-width:800px" ref="cateForm" :rules="itemRules" :model="item" label-width="80px">
      <el-form-item label="商品名称" prop="itemName">
        <el-input v-model="item.itemName"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input-number v-model="item.price"></el-input-number>
      </el-form-item>
      <el-form-item label="库存" prop="store">
        <el-input-number v-model="item.store"></el-input-number>
      </el-form-item>
      <el-form-item label="所属分类">
        <el-select v-model="item.cateId" placeholder="请选择一个分类">
          <el-option
            v-for="cate in cates"
            :key="cate.id"
            :label="cate.cateName"
            :value="cate.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上下架">
        <el-switch v-model="item.onSale"></el-switch>
      </el-form-item>
      <el-form-item label="商品封面">
        <el-upload
          ref="upload"
          class="upload-demo"
          action="/api/upload"
          name="file"
          :auto-upload="false"
          :data="{
            a: 10,
            b: 20
          }"
          :before-upload="beforeFileUpload"
          :on-success="uploadSuccess"
         >
           <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
           <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <img :src="item.thumb" width="100" alt="">
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="item.desc" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="详情">
        <div id="editor-container">
          <quill-editor v-model="item.content"
              ref="myQuillEditor"
              :options="editorOption"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmitCate">提交</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCateLists, getItemDetail, updateItem } from '_api'
import { Quill } from 'vue-quill-editor'
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module'

Quill.register('modules/ImageExtend', ImageExtend)
export default {
  data () {
    return {
      cates: [],
      // 新增商品
      item: {
        itemName: '',
        price: 0,
        store: 0,
        desc: '',
        cateId: -1,
        onSale: true,
        thumb: '',
        content: ''
      },
      itemRules: {
        // 表单验证
        itemName: [
          {
            required: true,
            message: '商品名称必填'
          }
        ],
        price: [
          {
            required: true,
            message: '商品价格必填'
          },
          {
            type: 'number',
            message: '商品价格是数字类型'
          }
        ],
        store: [
          {
            required: true,
            message: '商品库存必填'
          },
          {
            type: 'number',
            message: '商品库存是数字'
          }
        ],
        cateId: [
          {
            required: true,
            message: '分类id必选'
          }
        ]
      },
      editorOption: {
        // 富文本编辑器配置
        scrollingContainer: '#editor-container',
        modules: {
          ImageExtend: {
            loading: true,
            name: 'file',
            action: '/api/upload',
            response: (res) => {
              // 上传成功的回调中return 后端返回成功图片地址否则无法在编辑器回显图片
              return res.data
            }
          },
          toolbar: {
            container: container,
            handlers: {
              image: function () {
                QuillWatch.emit(this.quill.id)
              }
            }
          }
        }
      }
    }
  },
  methods: {
    getItemDetail () {
      // 获取商品详情
      getItemDetail({
        id: this.$route.query.id
      }).then(res => {
        if (res.data.code === 200) {
          this.item = res.data.data
          this.item.onSale = this.item.onSale === 0? true: false
          console.log(this.item, 111)
        }
      })
    },
    getCateLists () {
      // 获取所有分类
      getCateLists().then(res => {
        if (res.data.code === 200) {
          this.cates = res.data.data.cateList
        }
      })
    },
    beforeFileUpload (file) {
      // 上传前拦截
      if (file.size > 1024 * 500) {
        alert('请上传小于500kb的图片')
        return false
      } else {
        return true
      }
    },
    submitUpload () {
      // 点击手动上传分类图标
      this.$refs.upload.submit()
    },
    uploadSuccess (res, file) {
      // 图片上传成功回调
      if (res.code === 200) {
        this.item.thumb = res.data
      }
    },
    onSubmitCate () {
      /*
        判断表单的所有验证规则是否全部通过
        通过允许提交
      */
      this.$refs.cateForm.validate((valid) => {
        if (valid) {
          // 验证通过可以提交
          this.item.onSale = this.item.onSale ? 0 : 1
          updateItem(this.item).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: res.data.msg,
                duration: 1000,
                onClose: () => {
                  // 回到商品管理页
                  this.$router.replace('/itemLists')
                }
              })
            }
          })
        } else {
          return false
        }
      })
    }
  },
  created () {
    this.getCateLists()
    this.getItemDetail()
  }
}
</script>

<style lang="scss" scoped>
#editor-container{
  height: 400px;
  overflow-y:auto ;
}
::v-deep{
  .ql-container{
    min-height: 500px;
  }
}
</style>
